//引入模块
const express = require("express");
//引入连接池
const query = require("../util/query.js");
const JWT = require('../util/token.js');

//创建空路由器
let router = express.Router();
//=================================================
// 商品图片模块 
// 每个商品可以有多组图片，每组图片分别可以有小图、中图、大图
// ================================================
// 获取指定商品id的商品图片列表数据(数据量不多，就不作分页处理了)
// GET /product_image/list 
// 参数：product_id 
router.get("/list", async (req, res) => {
  try {
		let {product_id} = req.query;
		product_id = parseInt(product_id) || 0;
		
		if(!product_id) throw new Error("编号product_id不能为空");
    //建sql语句 
		//注意表xz_laptop_pic中的商品id属性名是laptop_id 返回时改为product_id了
    let sql = `SELECT id,laptop_id AS product_id,sm,md,lg FROM xz_laptop_pic WHERE laptop_id = ${product_id} ORDER BY id `;
		console.log(sql);
    //执行Query
    let result = await query(sql);
    //处理返回数据，（返回记录数量是0也是一种成功），响应对象    
    let data = result;//   
    res.send({
      code: 1,
      msg: "获取成功",
      data
    });
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//===============================================
//删除商品图片ById  
//GET /product_image/delete
//参数 id (图片id)
router.get("/delete", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;

  try {
    //获取数据
    let id = req.query.id;
		id = parseInt(id) ;
    //验证数据
    if (!id) throw new Error("编号Id不能为空");
    //执行SQL语句
    let sql = `DELETE FROM xz_laptop_pic WHERE id = ${id}`;
    let result = await query(sql);
    //根据sql操作影响的记录行数，判断是否删除成功
    if (result.affectedRows > 0) {
      res.send({ code: 1, msg: `删除成功 ：id=${id}` });
      return;
    }
    throw new Error(result.message || `没有编号为${id}的数据`);
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});


//===============================================
//修改/新增商品图片  如果id不空则修改，id空则新增
//POST /product_image/update
//参数 ：id,product_id,sm,md,lg(注意表xz_laptop_pic中的商品id属性名是laptop_id)
router.post("/update", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;

  try {
    //获取数据，验证数据,把传递过来的参数product_id改成laptop_id
    let product_image = req.body;
		product_image.laptop_id = product_image.product_id;
		delete product_image.product_id;
		product_image.id = parseInt(product_image.id) || 0 ;		
		
		//要确保product_image对象的属性和表xz_laptop_pic的字段属性名一致。
    //创建sql语句，并执行
    let sql = "";
    if (product_image.id) { //如果参数id有值的，则更新
      sql = `UPDATE xz_laptop_pic SET ? WHERE id=${product_image.id}`;
    } else { // 参数无id值，则新增记录
      sql = `INSERT INTO xz_laptop_pic SET ?`;
    }		
		
    let result = await query(sql, [product_image]);

    //根据sql操作影响的记录行数，判断是否删除成功
    if (result.affectedRows > 0) {
      if (!product_image.id) product_image.id = result.insertId; //如果是新增，设置新增的id			
      res.send({ code: 1, msg: "操作成功！", data: product_image.id });
      return;
    }
    throw new Error(result.message || `操作失败`);
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//==================================================
//导出路由器
module.exports = router;
